#include <createmymsg.h>


//之后将所有消息的正文格式都安排在一个json文件中,现在不会用c++做json

//MSGTYPE:;FROM:;TO:;CONTENT:[]!
void CreateReqLoginMsg(TransMsg &trans_msg, const char *from, const char* password){
    trans_msg.msg_type = REQ_LOGIN;
    strcpy(trans_msg.msg_from, from);
    strcpy(trans_msg.msg_to, "Server");
    strcpy(trans_msg.msg_content, password);

}

void CreateRspLoginMsg(TransMsg &trans_msg, const char * t, const char * content){
    trans_msg.msg_type = RSP_LOGIN;
    strcpy(trans_msg.msg_from, "Server");
    strcpy(trans_msg.msg_to, t);
    strcpy(trans_msg.msg_content, content);

}

void CreateReqRegistMsg(TransMsg &trans_msg, const char * from, const char * password){
    trans_msg.msg_type = REQ_REGIST;
    strcpy(trans_msg.msg_from, from);
    strcpy(trans_msg.msg_to, "Server");
    strcpy(trans_msg.msg_content, password);

}

void CreateRspRegistMsg(TransMsg &trans_msg, const char * t, const char * content){
    trans_msg.msg_type = RSP_REGIST;
    strcpy(trans_msg.msg_from, "Server");
    strcpy(trans_msg.msg_to, t);
    strcpy(trans_msg.msg_content, content);

}

void CreateMessageMsg(TransMsg &trans_msg, const char * from, const char * t, const char * content){
    trans_msg.msg_type = MESSAGE;
    strcpy(trans_msg.msg_from, from);
    strcpy(trans_msg.msg_to, t);
    strcpy(trans_msg.msg_content, content);

}

//客户端向服务器发送心跳;
void CreateReqHeartbMsg(TransMsg &trans_msg, const char * from){
    trans_msg.msg_type = REQ_HEARTB;
    strcpy(trans_msg.msg_from, from);
    strcpy(trans_msg.msg_to, "Server");
    time_t now = time(0);
    strcpy(trans_msg.msg_content, std::to_string(now).c_str());

}

void CreateRspHeartbMsg(TransMsg &trans_msg, const char * to, const char * content){
    trans_msg.msg_type = RSP_HEARTB;
    strcpy(trans_msg.msg_from, "Server");
    strcpy(trans_msg.msg_to, to);
    strcpy(trans_msg.msg_content, content);

}

//"name:1;name2:0;name:0;name:1;"
void SplitRspHeartbMsgContent(std::map<std::string , int> &a, std::string content){
    using namespace std;
    size_t start = 0;
    size_t end = 0;
    for (;start < content.length();){

        end = content.find(";", start);
        if (end == -1)break;
        //name:livetype;
        string sub = content.substr(start, end - start);
        string name = sub.substr(0, sub.find(":"));
        int v = atoi(sub.substr(sub.find(":") + 1).c_str());
        start = end + 1;
        //修改map;
        a[name] = v;
//        string sub = content.substring(end)
    }
}

void ShowTranslateMessage(const TransMsg &msg){
    using std::cout;
    cout << "type: " << msg.msg_type << " from: " << msg.msg_from << " to: " << msg.msg_to
              << " content: " << msg.msg_content <<"\n";
}
